package com.chinamsp.dydb.configuration;

import java.util.List;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;

import com.chinamsp.dydb.convert.ORMNameConverter;
import com.chinamsp.dydb.dbsource.DataSourceSettings;
import com.chinamsp.dydb.mybatis.interceptor.PaginationInterceptor;
import com.chinamsp.dydb.mybatis.interceptor.ShardingCheckedInterceptor;

@AutoConfigureAfter(DataSourceSettings.class)
public class MybatisInterceptorConfigration {

	@Autowired
	private List<SqlSessionFactory> sqlSessionFactoryList;
	
	@Autowired
	private DataSourceSettings dataSourceSettings;

	@Autowired
	private ORMNameConverter ormNameConverter;
	
	@PostConstruct
	public void addPageInterceptor() {
		// pagehelper 的 分页拦截器
		// 自己的分页拦截器
		PaginationInterceptor pi = new PaginationInterceptor();
		ShardingCheckedInterceptor sci = new ShardingCheckedInterceptor(ormNameConverter);
		pi.setProperties(new Properties());
		// 读写分离拦截器
		//DynamicDataSourceInterceptor ddi = new DynamicDataSourceInterceptor();
		for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
			sqlSessionFactory.getConfiguration().addInterceptor(pi);
			// 如果开启分库分表
			if (dataSourceSettings.isEnabledShardingChecked()){
				sqlSessionFactory.getConfiguration().addInterceptor(sci);
			}
			//sqlSessionFactory.getConfiguration().addInterceptor(ddi);
		}
	}
}
